﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace EasySocket
{
    public class EasySocketToken
    {
        private string _sessionId;
        private string _oldSessionId;
        private bool _isFirstReceive = true;

        public EasySocketToken(Socket socket)
        {
            Socket = socket;
        }

        public string SessionId => _sessionId;

        public string OldSessionId => _oldSessionId;

        public bool IsFirstReceive => _isFirstReceive;

        public Socket Socket { get; }

        public SemaphoreSlim Lock => new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(1, 1)).Value;

        public void SetSessionId(string sessionId)
        {
            _oldSessionId = _sessionId;
            _sessionId = sessionId;
        }

        internal void SetNotFirstReceive()
        {
            _isFirstReceive = false;
        }
    }

    public class AcceptContext
    {
        private EasySocketTcpServer _server;
        private string _sessionId;
        private string _oldSessionId;

        public AcceptContext( EasySocketTcpServer socketServer, IPEndPoint endPoint)
        {
            _server = socketServer;
            _sessionId = endPoint.ToString();
            RemoteEndPoint = endPoint;
        }

        /// <summary>
        /// true 拒绝此socket连接；false 接收
        /// </summary>
        public bool IsRefused {  get; set; }

        public IPEndPoint RemoteEndPoint { get; }

        public string SessionId => _sessionId;

        public string OldSessionId => _oldSessionId;

        public void SetSessionId(string sessionId)
        {
            _oldSessionId = _sessionId;
            _sessionId = sessionId;
        }

        public async Task SendAsync(string sessionId, byte[] data)
        {
            await _server.SendAsync(sessionId, data);
        }
    }

    public class EasySocketState
    {
        public EasySocketState(string sessionId, string oldSessionId, ConnectionStateEnum connectionState)
        {
            SessionId = sessionId;
            OldSessionId = oldSessionId;
            ConnectionState = connectionState;
        }

        public string SessionId { get; }

        public string OldSessionId { get; }

        public ConnectionStateEnum ConnectionState { get; }
    }

    public class EasySocketClientState
    {
        public EasySocketClientState(ConnectionStateEnum connectionState)
        {
            ConnectionState = connectionState;
        }

        public ConnectionStateEnum ConnectionState { get; }
    }
}